<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <!--<el-button type="primary" size="mini" @click="delAll">批量删除</el-button>-->
        <!--<el-input v-model="select_word" size="mini" placeholder="查询管理员（id,用户名，昵称）" class="handle-input"></el-input>-->
        <el-button type="primary" size="mini" @click="centerDialogVisible=true">添加方案</el-button>
      </div>
    </div>



    <el-table class="el-table_p" size="mini" ref="multipleTable" border :data="planList" :header-cell-style="{background:'#f4f3f9',color:'black',}">
      <el-table-column width="80" prop="num" label="序号" align="center"></el-table-column>
      <el-table-column prop="planName" label="方案名称" align="center"></el-table-column>
      <el-table-column prop="stageOne" label="第一阶段" align="center"></el-table-column>
      <el-table-column prop="stageTwo" label="第二阶段" align="center"></el-table-column>
      <el-table-column prop="stageOneRate" label="第一阶段提前还款比例" align="center" width="180px"></el-table-column>
      <el-table-column prop="serviceFeeRate" label="服务费比例" align="center"></el-table-column>
      <el-table-column prop="discountRate" label="提前还款优惠比例" align="center" width="130px"></el-table-column>
      <el-table-column prop="maxCoupon" label="最大优惠金额（元）" align="center" width="140px"></el-table-column>
      <el-table-column prop="paymentTerm" label="付款期限(天)" align="center" width="100px"></el-table-column>
      <el-table-column prop="applyOverdueCount" label="均摊+延期最大次数" align="center" width="140px"></el-table-column>
      <el-table-column label="操作" align="center" >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" class="template_btn" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" class="template_btn" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <el-dialog title="添加方案" :visible.sync="centerDialogVisible" width="400px" center>
      <el-form :model="registerForm" ref="registerForm" label-width="140px" :rules="rules">
        <el-form-item prop="planName" label="方案名称" size="mini">
          <el-input v-model="registerForm.planName" placeholder="方案名称"></el-input>
        </el-form-item>
        <el-form-item prop="stageOne" label="第一阶段" size="mini">
          <el-input v-model="registerForm.stageOne" placeholder="第一阶段(整数)" :readonly="readonly"></el-input>
        </el-form-item>

        <el-form-item prop="stageTwo" label="第二阶段" size="mini">
          <el-input v-model="registerForm.stageTwo" placeholder="第二阶段(整数)"></el-input>
        </el-form-item>
        <el-form-item prop="stageOneRate" label="第一阶段比例" size="mini">
          <el-input v-model="registerForm.stageOneRate" placeholder="第一阶段比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="serviceFeeRate" label="服务费比例" size="mini">
          <el-input v-model="registerForm.serviceFeeRate" placeholder="服务费比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="discountRate" label="优惠比例" size="mini">
          <el-input v-model="registerForm.discountRate" placeholder="优惠比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="maxCoupon" label="最大优惠" size="mini">
          <el-input v-model="registerForm.maxCoupon" placeholder="最大优惠"></el-input>
        </el-form-item>

        <el-form-item prop="paymentTerm" label="还款期限" size="mini">
          <el-input v-model="registerForm.paymentTerm" placeholder="还款期限"></el-input>
        </el-form-item>
        <el-form-item prop="applyOverdueCount" label="均摊/延期次数" size="mini">
          <el-input v-model="registerForm.applyOverdueCount" placeholder="均摊/延期次数"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="centerDialogVisible = false">取消</el-button>
                <el-button size="mini" @click="addPlan" type="primary">确定</el-button>
            </span>
    </el-dialog>
    <el-dialog title="编辑方案" :visible.sync="editVisible" width="400px" center>
      <el-form :model="form" ref="form" label-width="140px" :rules="rules">
        <el-form-item prop="planName" label="方案名称" size="mini">
          <el-input v-model="form.planName" placeholder="方案名称"></el-input>
        </el-form-item>
        <el-form-item prop="stageOne" label="第一阶段" size="mini">
          <el-input v-model="form.stageOne" placeholder="第一阶段(整数)" :readonly="readonly"></el-input>
        </el-form-item>

        <el-form-item prop="stageTwo" label="第二阶段" size="mini">
          <el-input v-model="form.stageTwo" placeholder="第二阶段(整数)"></el-input>
        </el-form-item>
        <el-form-item prop="stageOneRate" label="第一阶段比例" size="mini">
          <el-input v-model="form.stageOneRate" placeholder="第一阶段比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="serviceFeeRate" label="服务费比例" size="mini">
          <el-input v-model="form.serviceFeeRate" placeholder="服务费比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="discountRate" label="优惠比例" size="mini">
          <el-input v-model="form.discountRate" placeholder="优惠比例(小数)"></el-input>
        </el-form-item>
        <el-form-item prop="maxCoupon" label="最大优惠" size="mini">
          <el-input v-model="form.maxCoupon" placeholder="最大优惠"></el-input>
        </el-form-item>
        <el-form-item prop="paymentTerm" label="还款期限" size="mini">
          <el-input v-model="form.paymentTerm" placeholder="还款期限"></el-input>
        </el-form-item>
        <el-form-item prop="applyOverdueCount" label="均摊/延期次数" size="mini">
          <el-input v-model="form.applyOverdueCount" placeholder="均摊/延期次数"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
                <el-button size="mini" @click="editVisible = false">取消</el-button>
                <el-button size="mini" @click="updatePlan" type="primary">确定</el-button>
            </span>
    </el-dialog>


    <el-dialog title="删除方案" :visible.sync="delVisible" width="400px" center>
      <div align="center">删除不可恢复，是否确定删除方案<sapn style="font-size: 18px;color: red;font-weight: bold">{{planName}}</sapn>？</div>
      <span slot="footer">
                <el-button size="mini" @click="delVisible = false">取消</el-button>
                <el-button size="mini" @click="deleteRow" type="primary">确定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getPlanList, addPlan, updatePlan, delPlan} from '../../api/public/api';
  import {mixin} from '../../../static/js/index';

  export default {
    mixins: [mixin],
    data() {
      var valiNumber1 = (rule, value, callback) => {//包含小数的数字
        let reg = /^[+]?(0|([1-9]\d*))(\.[\d+]{1,2})?$/g;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value) || value < 0) {
          callback(new Error('请输入正确的数字（最多两位小数）'));
        } else {
          callback();
        }
      };
      // 阶段
      var valiNumber2 = (rule, value, callback) => {
        let reg = /^([1-9]\d*|[0])$/;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入正确的整数'));
        } else {
          callback();
        }
      };
      //比例
      var valiNumber3 = (rule, value, callback) => {//包含小数的数字 <1
        let reg = /^[+]?(0|([1-9]\d*))(\.[\d+]{1,2})?$/g;
        if (value === '') {
          callback(new Error('请输入内容'));
        } else if (!reg.test(value) || value < 0 || value > 1) {
          callback(new Error('请输入小数，0到1）'));
        } else {
          callback();
        }
      };
      //判断方案名是否存在
      // const userNameCheck1 = (rule, value, callback) => {
      //   if(value!=''){
      //     getByName(value).then(res=>{
      //       if (res.data.code!=0) {
      //         callback(new Error('该用课程名已存在，请重新输入'));
      //       } else {
      //         callback();
      //       }
      //     })
      //   }else {
      //     callback(new Error('请输入课程名'));
      //   }
      // };
      return {
        level: 0,
        planList: [],
        readonly: true,
        registerForm: {
          "planName": "",//添加框
          "stageOne": 6,
          "stageTwo": 0,
          "stageOneRate": 0,
          "serviceFeeRate": 0,
          "discountRate": 0,
          "maxCoupon": 0,
          "paymentTerm": 3,
          "applyOverdueCount": 3

        },
        form: {      //编辑框
          "planName": "",//添加框
          "stageOne": 6,
          "stageTwo": 0,
          "stageOneRate": 0,
          "serviceFeeRate": 0,
          "discountRate": 0,
          "maxCoupon": 0,
          "paymentTerm": 3,
          "applyOverdueCount": 3
        },
        id: "",
        centerDialogVisible: false, //添加弹窗是否显示
        editVisible: false,         //编辑弹窗是否显示
        delVisible: false,          //删除弹窗是否显示
        rules: {
          planName: [
            {required: true, message: '请输入方案名', trigger: 'blur'}
          ],
          stageOne: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],
          stageTwo: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],
          stageOneRate: [
            {required: true, validator: valiNumber3, trigger: 'blur'}
          ],
          serviceFeeRate: [
            {required: true, validator: valiNumber3, trigger: 'blur'}
          ],
          discountRate: [
            {required: true, validator: valiNumber3, trigger: 'blur'}
          ],
          maxCoupon: [
            {required: true, validator: valiNumber1, trigger: 'blur'}
          ],

          paymentTerm: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],
          applyOverdueCount: [
            {required: true, validator: valiNumber2, trigger: 'blur'}
          ],

        },
        planName:""
      }
    },
    created() {
      let data = {}
      this.getData(data);
      this.level = localStorage.getItem('level')
    },
    methods: {
      updateData() {
        let data = {}
        this.getData(data);
      },
      //查询所有管理员
      getData(data) {
        getPlanList(data).then(res => {
          console.log(res)
          if (res.data.code == 0) {
            let num=1
            res.data.data.records.map(item => {
              const t = new Date(item.createTime)
              const y = t.getFullYear()
              const m = t.getMonth() + 1
              const d = t.getDate()
              item.num = num++
              item.createTime = y + "-" + m + "-" + d
            })
            this.planList = res.data.data.records
            console.log(this.planList)
          }


        })
      },
      //添加管理员
      addPlan() {
        this.centerDialogVisible = true
        this.$refs['registerForm'].validate(valid => {
          if (valid) {
            let params = this.registerForm
            addPlan(params)
              .then(res => {
                console.log(res)
                if (res.data.code == 0) {
                  this.centerDialogVisible = false;
                  this.notify("添加成功", "success");
                  this.updateData()
                } else {
                  this.notify(res.data.msg, "error");
                }
              })
              .catch(err => {
                console.log(err);
              });

          }
        })

      },
      //弹出编辑页面
      handleEdit(row) {
        this.id = row.id
        this.editVisible = true;
        this.form = row

      },
      //保存编辑页面修改的数据
      updatePlan() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            let params = {
              "id": this.id,
              "planName": this.form.planName,
              "stageOne": this.form.stageOne,
              "stageTwo": this.form.stageTwo,
              "stageOneRate": this.form.stageOneRate,
              "serviceFeeRate": this.form.serviceFeeRate,
              "discountRate": this.form.discountRate,
              "maxCoupon": this.form.maxCoupon,
              "paymentTerm": this.form.paymentTerm,
              "applyOverdueCount": this.form.applyOverdueCount
            };
            // let params = this.form

            updatePlan(params).then(res => {
              if (res.data.code == 0) {
                this.editVisible = false;
                this.notify("修改成功", "success");
              } else {
                this.notify(res.data.msg, "error");
              }
              this.updateData()
            })
              .catch(err => {
                console.log(err);
              });

          }
        })

      },

      //删除
      handleDelete(row) {
        this.id = row.id
        this.delVisible = true
        this.planName=row.planName
        console.log(this.planName)
      },
      deleteRow() {

        delPlan(this.id)
          .then(res => {
            if (res.data.code == 0) {
              this.delVisible = false;
              this.updateData()
              this.notify("删除成功", "success");
            } else {
              this.notify(res.data.msg, "error");
            }
          })
          .catch(err => {
            console.log(err);
          });

      },
      //转向该用户的收藏列表
      getCollect(id) {
        this.$router.push({path: '/collect', query: {id}})
      },
      //表头行的设置
      tableHeaderColor({row,column,rowIndex,columnIndex}){
        return 'background-color:#fff;font-wight:500;font-size:13px;text-align:center;height:50px'
      },
    }
  }
</script>

<style scoped>
  .handle-box {
    margin-bottom: 20px;
  }

  .template_btn {
    margin-bottom: 10px !important;
    margin-left: 0 !important;
  }
</style>
